#include "spi.h"

void SPI1_Init(void)
{	 
  GPIO_InitTypeDef  GPIO_InitStructure;
  SPI_InitTypeDef  SPI_InitStructure;
	
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);               //Enable related clock - GPIOB, SPI1
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);            
 
 
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3|GPIO_Pin_4|GPIO_Pin_5;     //PB3~5 multiplexed as SPI1
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;                    
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;                      //Push-pull output
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;                  //100MHz
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;                        //pull up
  GPIO_Init(GPIOB, &GPIO_InitStructure);                              //Initialize the IO 
  GPIO_PinAFConfig(GPIOB,GPIO_PinSource3,GPIO_AF_SPI1);           
  GPIO_PinAFConfig(GPIOB,GPIO_PinSource4,GPIO_AF_SPI1);           
  GPIO_PinAFConfig(GPIOB,GPIO_PinSource5,GPIO_AF_SPI1);           
 
	                                                                  //Initialize the SPI
	RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1,ENABLE);               //reset SPI1
	RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1,DISABLE);              //stop reset 

	SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;//Two-line full-duplex
	SPI_InitStructure.SPI_Mode = SPI_Mode_Master;		              
	SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;		          
	SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;		                  
	SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;	                  
	SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;		                  
	SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
	SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;	              
	SPI_InitStructure.SPI_CRCPolynomial = 7;	                      
	SPI_Init(SPI1, &SPI_InitStructure);                               //Initialize SPIx register
 
	SPI_Cmd(SPI1, ENABLE);                                            //enable SPI

	SPI1_ReadWriteByte(0xff);                                         //Start transfer	 
} 

//SPI_Prescaler - (SPI_BaudRatePrescaler_2, SPI_BaudRatePrescaler_256)
void SPI1_Setclock(u8 SPI_Prescaler)
{
    assert_param(IS_SPI_BAUDRATE_PRESCALER(SPI_Prescaler));
	SPI1->CR1&=0XFFC7;                           
	SPI1->CR1|=SPI_Prescaler;	                  
	SPI_Cmd(SPI1,ENABLE);                        
} 


u8 SPI1_ReadWriteByte(u8 writeData)
{		 			 
   u8 waitnum=0;
  while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET)
	    {
        waitnum++;
        if (waitnum > 200) return 0;
    }  

	SPI_I2S_SendData(SPI1, writeData);  
		
  while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET){} 
	  	    {
        waitnum++;
        if (waitnum > 200) return 0;
    }  

	return SPI_I2S_ReceiveData(SPI1);  
 		    
}

